package com.jxs.android.sxyw;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.sxyw.AbstractListActivity.DataInitListeren;
import com.jxs.android.sxyw.boot.SelfApplication;
import com.jxs.android.sxyw.data.CaseAttachmentInfo;
import com.jxs.android.sxyw.data.CaseInfo;
import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.RefreshListView;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.FileHloder;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.util.SysUpdateHolder;

/**
 * @Des EOMS 告警
 * @Author jiangxs
 * @Des 2012-8-20 下午2:03:35
 */
public class CaseAttachmentList extends AbstractActivity {

	private static final int UPDATE_LIST_UI = 0x101;
	private static final int ERROR_MSG = 0x1013;
	private static final int TO_LOGIN = 0x109;

	private String ticket = "";

	private RefreshListView refreshListView;
	private TextView empytText;
	private AttachmentAdapter attachmentAdapter;
	private CaseInfo caseInfo;

	private int currentPage = 1; // 最后的可视项索引

	private DownLoadFileOverReceiver downLoadFileOverReceiver = new DownLoadFileOverReceiver();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.common_with_list);
		if (null == SelfApplication.getUserInfo() || StringUtils.isEmpety(SelfApplication.getUserInfo().getTicket())) {
			PopMsg.show("登录已过期,请重新登录");
			StartHelper.startActivity(Login.class);
			return;
		}

		refreshListView = (RefreshListView) findViewById(R.id.common_listview);
		empytText = (TextView) findViewById(R.id.null_has_data);
		empytText.setText(empytTip());
		attachmentAdapter = new AttachmentAdapter();
		refreshListView.setAdapter(attachmentAdapter);
		ticket = SelfApplication.getUserInfo().getTicket();

		if (null != getIntent() && null != getIntent().getExtras()) {
			caseInfo = (CaseInfo) getIntent().getExtras().get("caseInfo");
		}

		loadingData(caseInfo);
		refreshListView.setonRefreshListener(new RefreshListView.OnRefreshListener() {
			@Override
			public void onRefresh() {
				loadingData(caseInfo);
			}
		});
		registerReceiver(downLoadFileOverReceiver, new IntentFilter(SysUpdateHolder.DOWN_LOAD_FILE_OVER_ACTION));
	}

	private void loadingData(CaseInfo caseInfo) {
		CaseAttachmentList.this.getWebServiceData(ticket, caseInfo, new DataInitListeren() {
			@Override
			public void initData(ProgressDialog progressDialog, boolean isShow) {
				if (isShow) {
					progressDialog.dismiss();
				}
			}
		});
	}

	protected void getWebServiceData(final String ticket, final CaseInfo caseInfo, final DataInitListeren dataInitListeren) {

		final ProgressDialog progressDialog = ProgressDialog.show(this, "", "正在加载，请稍候...", true);
		progressDialog.setCancelable(true);
		new Thread() {
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				getListData(ticket, caseInfo);
				dataInitListeren.initData(progressDialog, true);
			}
		}.start();
	}

	protected void getListData(String ticket, CaseInfo caseInfo) {
		String wsdl_url = SelfApplication.WSDL_URL;// wsdl
		String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getFileOfWorkOrder";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("order_id", caseInfo.getOrder_id());
		request.addProperty("workOrderType", caseInfo.getOrderType().index + "");

		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}
		});
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.setTitle("附件");
		initTopBarReturn(topBar);
		topBar.hindBtn();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getPropertySafelyAsString("status");
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getPropertySafelyAsString("message");
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				List<CaseAttachmentInfo> attachments = new ArrayList<CaseAttachmentInfo>();

				/*
				 * CaseAttachmentInfo ainfo = new CaseAttachmentInfo();
				 * ainfo.setFile_id("hhh.jpg"); ainfo.setFile_name("hhh.jpg");
				 * ainfo.setFile_size("file_size");
				 * ainfo.setCreat_time("creat_time");
				 * ainfo.setUser_name("user_name"); ainfo.setPath(
				 * "http://pic.nipic.com/2007-09-11/20079119592229_2.jpg");
				 * attachments.add(ainfo);
				 * 
				 * ainfo = new CaseAttachmentInfo();
				 * ainfo.setFile_id("hhh.jpg");
				 * ainfo.setFile_name("gjjpkcsbcl.ppt");
				 * ainfo.setFile_size("file_size");
				 * ainfo.setCreat_time("creat_time");
				 * ainfo.setUser_name("user_name"); ainfo.setPath(
				 * "http://www.ccucm.edu.cn/jpk/jpk_fj/ppt/gjjpkcsbcl.ppt");
				 * 
				 * attachments.add(ainfo);
				 */

				SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");
				if (null != retMsgObject) {
					for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
						SoapObject attachmentBeanObject = (SoapObject) retMsgObject.getProperty(i);
						CaseAttachmentInfo attachment = new CaseAttachmentInfo();
						attachment.setFile_id(attachmentBeanObject.getPropertySafelyAsString("file_id"));
						attachment.setFile_name(attachmentBeanObject.getPropertySafelyAsString("file_name"));
						attachment.setFile_size(attachmentBeanObject.getPropertySafelyAsString("file_size"));
						attachment.setCreat_time(attachmentBeanObject.getPropertySafelyAsString("creat_time"));
						attachment.setUser_name(attachmentBeanObject.getPropertySafelyAsString("user_name"));
						attachment.setPath(attachmentBeanObject.getPropertySafelyAsString("path"));

						attachments.add(attachment);
					}
				}
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = attachments;
				handler.sendMessage(msg);
			}
		}
	}

	Handler handler = new Handler() {

		@Override
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_LIST_UI) {

				List<CaseAttachmentInfo> tems = (List<CaseAttachmentInfo>) msg.obj;
				empytText.setVisibility(View.GONE);
				attachmentAdapter.setAttachments(tems);
				attachmentAdapter.notifyDataSetChanged();

				if (currentPage == 1) {
					if (tems.size() < 1) {
						empytText.setVisibility(View.VISIBLE);
					}
				}
				refreshListView.onRefreshComplete();
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == TO_LOGIN) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(Login.class);
			}
		}

	};

	private String empytTip() {
		return "暂无附件信息";
	}

	private class AttachmentAdapter extends BaseAdapter {

		private List<CaseAttachmentInfo> attachments = new ArrayList<CaseAttachmentInfo>();

		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public void setAttachments(List<CaseAttachmentInfo> contacts) {
			this.attachments.clear();
			this.attachments.addAll(contacts);
		}

		public AttachmentAdapter() {
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return attachments.size();
		}

		public CaseAttachmentInfo getItem(int position) {
			return attachments.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			final CaseAttachmentInfo taskInfo = attachments.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.attachment_list_item, null);
				holder = new ViewHolder();
				holder.file_name = (TextView) convertView.findViewById(R.id.file_name);
				holder.file_size = (TextView) convertView.findViewById(R.id.file_size);
				holder.creat_time = (TextView) convertView.findViewById(R.id.creat_time);
				holder.user_name = (TextView) convertView.findViewById(R.id.user_name);
				holder.list_menu = (ImageView) convertView.findViewById(R.id.item_arrow);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.file_name.setText(taskInfo.getFile_name());
			long size = 0;
			if (!StringUtils.isEmpety(taskInfo.getFile_size())) {
				String temp = StringUtils.getStringDigits(taskInfo.getFile_size());
				if (StringUtils.isEmpety(temp)) {
					temp = "0";
				}
				size = Long.valueOf(temp);
			}
			holder.file_size.setText(FileHloder.FormetFileSize(size));
			holder.creat_time.setText(taskInfo.getCreat_time());
			holder.user_name.setText(taskInfo.getUser_name());

			OnClickListener onClickListener = new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					onclickView(position, taskInfo);
				}
			};

			holder.list_menu.setOnClickListener(onClickListener);
			convertView.setOnClickListener(onClickListener);
			if (position == 0) {
				convertView.setBackgroundResource(R.drawable.roundlist_head);
			} else if (position == attachments.size() - 1) {
				convertView.setBackgroundResource(R.drawable.roundlist_tail);
			} else {
				convertView.setBackgroundResource(R.drawable.roundlist_body);
			}
			return convertView;
		}

		private void onclickView(int position, CaseAttachmentInfo attacheInfo) {
			if (!FileHloder.hasDownFile(attacheInfo.getFile_id() + "_" + attacheInfo.getFile_name())) {
				SysUpdateHolder.downLoadFile(CaseAttachmentList.this, "正在下载，请稍后...", attacheInfo.getPath(), FileHloder.ROOT + "/download/" + attacheInfo.getFile_id() + "_" + attacheInfo.getFile_name());
			} else {
				Intent intent = FileHloder.openFile(FileHloder.DIR_DOWN + attacheInfo.getFile_id() + "_" + attacheInfo.getFile_name());
				if (null != intent) {
					startActivity(intent);
				} else {
					PopMsg.show("文件未下载成功，请重新下载！");
				}
			}
		}

		class ViewHolder {
			TextView file_name;// 文件名称
			TextView file_size;// 文件大小
			TextView creat_time;// 创建时间
			TextView user_name;// 创建人
			ImageView list_menu;//
		}

	}

	private class DownLoadFileOverReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (null != intent && null != intent.getExtras()) {
				PopMsg.show("文件已下载,点击附件，直接打开!");
			}

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(downLoadFileOverReceiver);
	}

}
